package com.phonegap.breastmilk;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.phonegap.breastmilk.R;

import android.app.Activity;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class AdapterJournal extends SimpleCursorAdapter {
	
	//private static String[] from = new String [] {"_id","date_begin","date_end","breast_fed","notes"};
	private static int[] to = new int[] {R.id.textViewValStartTime};
	private Activity context;
	private static AdapterJournal adapterJournal = null;
    
	private AdapterJournal(Activity context, Cursor cursor, String[] from, int[] to) {
		super(context, R.layout.listitem, cursor, from, to);
		this.context = context;
	}
	
	public static AdapterJournal getInstance(Activity context, Cursor cursor, String[] from) {
		if (adapterJournal == null) {
			adapterJournal = new AdapterJournal(context, cursor, from, to);
		}
		return adapterJournal;
	}
	
	public View getView(int position, View convertView, ViewGroup parent) {
		View item = convertView;
		ViewHolder holder;
		
		if (item == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			item = inflater.inflate(R.layout.listitem, null);
			
			holder = new ViewHolder();
	        holder.titulo = (TextView)item.findViewById(R.id.labelTitulo);
	        holder.subtitulo = (TextView)item.findViewById(R.id.labelSubTitulo);
	 
	        item.setTag(holder);
		} else {
	        holder = (ViewHolder)item.getTag();
	    }
		this.getCursor().moveToPosition(position);
		String dateBegin = this.getCursor().getString(1);
		String dateEnd = this.getCursor().getString(2);
		Pattern p = Pattern.compile("([\\w]+\\s[\\w]+\\s[0-9]+)\\s([0-9]+:[0-9]+:[0-9]+).*\\s([0-9]+)$");
		
		Matcher m1 = p.matcher(dateBegin);
		if (m1.find()) {
			holder.titulo.setText(m1.group(1) + ", " + m1.group(3) + " - " + this.getCursor().getString(3));
		}
		
		Matcher m2 = p.matcher(dateEnd);
		if (m2.find()) {
			holder.subtitulo.setText(m1.group(2) + " - " + m2.group(2));
		}
		
		return(item);
	}
	
	static class ViewHolder {
    	TextView titulo;
    	TextView subtitulo;
    }
}
